﻿"""
Configuration management for the application.
Loads environment variables and provides centralized config access.
"""
from typing import Any

from pydantic import Field, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Application settings and configuration."""

    model_config = SettingsConfigDict(
        env_file=".env",
        case_sensitive=True,
        env_parse_enums=False,
    )

    # Application
    APP_NAME: str = "Meeting Room Booking System"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = Field(default=False, env="DEBUG")

    # Database
    DATABASE_URL: SecretStr = Field(..., env="DATABASE_URL")

    # Security
    SECRET_KEY: SecretStr = Field(..., env="SECRET_KEY")
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30

    # CORS
    CORS_ORIGINS: list[str] = [
        "http://localhost",
        "http://localhost:80",
        "http://localhost:3000",
        "http://localhost:5173",
        "http://localhost:8080",
        "http://127.0.0.1",
        "http://127.0.0.1:80",
        "http://localhost:8001",
        "http://127.0.0.1:8001",
    ]

    @field_validator("DATABASE_URL", "SECRET_KEY")
    @classmethod
    def _validate_required_secret(cls, value: SecretStr) -> SecretStr:
        """Ensure mandatory secrets are provided and non-empty."""
        secret_value = value.get_secret_value().strip()
        if not secret_value:
            raise ValueError("Value cannot be empty.")
        return SecretStr(secret_value)

    @field_validator("CORS_ORIGINS", mode="before")
    @classmethod
    def parse_cors_origins(cls, v: Any) -> list[str]:
        """Parse CORS_ORIGINS from comma-separated string or JSON array."""
        if isinstance(v, str):
            # Try to handle both comma-separated and JSON array formats
            v = v.strip()
            if v.startswith("[") and v.endswith("]"):
                # Already in JSON format, let Pydantic parse it
                import json

                try:
                    return json.loads(v)
                except json.JSONDecodeError:
                    pass
            # Fallback to comma-separated format
            return [origin.strip() for origin in v.split(",") if origin.strip()]
        if isinstance(v, list):
            return v
        return []

    @property
    def database_url(self) -> str:
        """Return the decrypted database URL."""
        return self.DATABASE_URL.get_secret_value()

    @property
    def secret_key(self) -> str:
        """Return the decrypted application secret key."""
        return self.SECRET_KEY.get_secret_value()

    def cors_allow_origin_regex(self) -> str:
        """Return regex pattern for CORS origins to allow server IP access."""
        return r"https?://(localhost|127\.0\.0\.1|\d+\.\d+\.\d+\.\d+)(:\d+)?"


# Global settings instance
settings = Settings()
